const express = require("express")
let router = express.Router()
const ArticleCateModel = require("../../model/ArticleCateModel")
const ArticleModel = require("../../model/ArticleModel")

const { multer, getUnix } = require("../../model/tools")

router.get("/", async (req, res) => {

    let page = req.query.page || 1  // 查询第几页的数据
    let pageSize = 8                // 一页显示几条数据

    let json = {}                       // 用作搜索

    let keywords = req.query.keywords

    if (keywords) {
        json = Object.assign(json, { "title": { $regex: new RegExp(keywords) } })
    }


    // 数据分页查询
    // let result = await ArticleModel.find({}).skip((page - 1) * pageSize).limit(pageSize)

    // 数据关联分页查询
    let result = await ArticleModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: "cid",
                foreignField: "_id",
                as: "cate"
            }
        }, {
            $match: json
        }, {
            $sort: { "add_time": -1 }
        }, {
            $skip: (page - 1) * pageSize
        }, {
            $limit: pageSize
        }

    ])

    let count = await ArticleModel.count(json)

    res.render("admin/article/index.html", {
        list: result,
        totalPages: Math.ceil(count / pageSize),
        page,
        keywords
    })
})

router.get("/add", async (req, res) => {
    let result = await ArticleCateModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: "_id",
                foreignField: "pid",
                as: "items"
            }
        },
        {
            $match: {
                pid: "0"
            }
        }
    ])
    res.render("admin/article/add.html", {
        articleCate: result
    })
})

router.post("/doAdd", multer().single('article_img'), async (req, res) => {
    let imgSrc = req.file && req.file.path.substr(7)

    let result = new ArticleModel(Object.assign(req.body, { "article_img": imgSrc }, { "add_time": getUnix() }))
    await result.save()

    res.redirect(`/${req.app.locals.adminPath}/article`)
})

router.get("/edit", async (req, res) => {
    // 获取要修改的数据
    let id = req.query.id
    let articleResult = await ArticleModel.find({ "_id": id })

    // 获取分类信息
    let cateResult = await ArticleCateModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: "_id",
                foreignField: "pid",
                as: "items"
            }
        },
        {
            $match: {
                pid: "0"
            }
        }
    ])
    res.render("admin/article/edit.html", {
        articleCate: cateResult,
        list: articleResult[0]
    })
})

router.post("/doEdit", multer().single('article_img'), async (req, res) => {
    // 判断是否有修改图片
    if (req.file) {
        let imgSrc = req.file && req.file.path.substr(7)
        await ArticleModel.updateOne({ "_id": req.body.id }, Object.assign(req.body, { "article_img": imgSrc }))

    } else {
        await ArticleModel.updateOne({ "_id": req.body.id }, req.body)
    }

    res.redirect(`/${req.app.locals.adminPath}/article`)
})

router.get("/delete", async (req, res) => {
    let id = req.query.id

    let resultList = await ArticleModel.find({ "_id": id })
    let delResult = await ArticleModel.deleteOne({ "_id": id })

    // 顺带删除upload文件夹的文件
    if (delResult.ok === 1 && delResult.n === 1) {
        if (resultList[0].focus_img) {
            fs.unlink("static/" + resultList[0].focus_img, (err) => {
            })
        }
    }

    if (delResult) {
        res.render('admin/public/success', {
            "message": '删除内容数据成功',
            "redirectUrl": `/${req.app.locals.adminPath}/article`
        })
    }
})

// 富文本编辑器上传图片
router.post("/doUploadImage", multer().single('file'), async (req, res) => {
    let imgSrc = req.file && req.file.path.substr(7)

    res.send({
        link: "/" + imgSrc
    })
})
module.exports = router